On this page
Inline Assembly
The
asm!macro allows Rust to directly embed target machine assembly instructions—constraints describe the input/output relationships of registers, and clobbers declare which registers are clobbered. Each assembly template is per-architecture (x86_64 and ARM64 syntaxes differ completely), essentially acting as a wall to the compiler optimizer saying "please do not optimize across this line."
asm! Basics
use asm;
let x: u64;
unsafe
// TSC (Time Stamp Counter) = EDX:EAX
// out("rax") _ — upper 32 bits, value discarded (_)
// out("rdx") _ — lower 32 bits in rdx, discarded
// lateout("rax") x — value combined in x
asm! is a new macro introduced in Rust 1.59+ (replacing the old llvm_asm!). It performs compile-time checks for constraint correctness—register conflicts, invalid operands, and type mismatches are all reported at compile time.
Constraints: Input/Output Specifications
let mut a: u64 = 4;
let b: u64 = 4;
unsafe
in(reg): Input, compiler allocates a register and loads the valueout(reg): Output, reads the final valueinout(reg): Input + Outputlateout(reg): Output, does not share a register with inputs (used when input registers are clobbered)inlateout(reg): Input + Output, does not share a register with inputs
Clobbers: Which Registers Are Modified
out and lateout automatically mark the corresponding registers as clobbered. However, if other functions are called, you need to mark the entire ABI's clobber set:
unsafe
Per-Architecture Conditional Compilation
unsafe
unsafe // ARM64 cycle counter
Options
asm!;
// nomem: No memory read/write (compiler may not flush cache)
// nostack: No push/pop to stack
// preserves_flags: Does not modify EFLAGS/RFLAGS
// pure: No side effects (can be optimized away)
// readonly: Read-only memory
References
- Rust Reference: inline assembly
- Rust By Example: asm
Keywords: asm!, inline assembly, constraints, clobbers, lateout, clobber_abi, per-arch asm